﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Treca.Business;
using Treca.Business.Base_SysManage;
using Treca.PushMessage.Base;
using Treca.PushMessage.Base.Base;
using Treca.PushMessage.Business;
using Treca.Util;
using Treca.WebBase;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.Helpers;

namespace Treca.Web.Areas.Base_SysManage.Controllers
{
    [Area("PushMessage")]
    [Route("PushMessage/[controller]/[action]")]
    public partial class MessageApiController : BaseApiController
    {
        public static readonly string Token = "89D79BD5E495A60E";//与微信公众账号后台的Token设置保持一致，区分大小写。
        public static readonly string EncodingAESKey = "ah5c21pg0itQDkEk1gCNbLCoGod1ZdvKSCi5tEr5d0U";//与微信公众账号后台的EncodingAESKey设置保持一致，区分大小写。
        public static readonly string AppId = "wx5053cc65965bca3b";//与微信公众账号后台的AppId设置保持一致，区分大小写。


        //public static readonly string WAPP_Token = "89D79BD5E495A60E";//与微信公众账号后台的Token设置保持一致，区分大小写。
        //public static readonly string WAPP_EncodingAESKey = "cc6ca07709fc9298c549a32888f1cdfe";//与微信公众账号后台的EncodingAESKey设置保持一致，区分大小写。
        public static readonly string WAPP_AppSecret = "cc6ca07709fc9298c549a32888f1cdfe";//与微信公众账号后台的EncodingAESKey设置保持一致，区分大小写。
        public static readonly string WAPP_AppId = "wxced1b0a3375f27b3";//与微信公众账号后台的AppId设置保持一致，区分大小写。

        public MessageApiController(ICustomAuthenticationManager _authm)
        {
            authm = _authm;
        }
        ICustomAuthenticationManager authm { get; }
        /// <summary>
        /// 微信后台验证地址（使用Get），微信后台的“接口配置信息”的Url填写如：http://weixin.senparc.com/weixin
        /// </summary>
        [HttpGet]
        [IgnoreJWT]
        public ActionResult Get([FromQuery]PostModel postModel, string echostr)
        {
            if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                return Content(echostr); //返回随机字符串则表示验证通过
            }
            else
            {
                return Content("failed:" + postModel.Signature + "," + Senparc.Weixin.MP.CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, Token) + "。" +
                    "如果你在浏览器中看到这句话，说明此地址可以被作为微信公众账号后台的Url，请注意保持Token一致。");
            }
        }
        public class openseeion {
            public string  session_key {get;set;}
            public string openid { get; set; }
        }
        /// <summary>
        /// 微信后台验证地址（使用Get），微信后台的“接口配置信息”的Url填写如：http://weixin.senparc.com/weixin
        /// </summary>
        [HttpGet]
        [IgnoreJWT]
        public AjaxResult WeiXinLogin(string js_code)
        {
            Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
            keyValuePairs.Add("appid", WAPP_AppId);
            keyValuePairs.Add("secret", WAPP_AppSecret);
            keyValuePairs.Add("js_code", js_code);
            var str= HttpHelper.PostData("https://api.weixin.qq.com/sns/jscode2session", keyValuePairs, null, ContentType.Form);
            openseeion openid= str.ToObject<openseeion>();
            var res=authm.Authenticate(openid.openid);
            if (!res.Success)
            {
                return AjaxHelper.Error(res.Msg, openid.openid);
            }
            else
            {
                return AjaxHelper.Success(res.Msg, openid.openid);
            }
        }


        IOperator @operator { get => AutofacHelper.GetScopeService<IOperator>(); }
        [HttpGet]
        public AjaxResult GetUserInfo()
        {
            var prop = @operator.Property;
            return AjaxHelper.Success(prop);
        }


        /// <summary>
        /// 用户发送消息后，微信平台自动Post一个请求到这里，并等待响应XML。
        /// PS：此方法为简化方法，效果与OldPost一致。
        /// v0.8之后的版本可以结合Senparc.Weixin.MP.MvcExtension扩展包，使用WeixinResult，见MiniPost方法。
        /// </summary>
        [HttpPost]
        [IgnoreJWT]
        public ActionResult Post(PostModel postModel)
        {
            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                return Content("参数错误！");
            }

            postModel.Token = Token;//根据自己后台的设置保持一致
            postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致
            postModel.AppId = AppId;//根据自己后台的设置保持一致
            var stream = Request.Body;
            XDocument xml = new XDocument();
            using (var reader = new StreamReader(stream, Encoding.UTF8))
            {
                //Request.EnableBuffering();
                var param = reader.ReadToEndAsync().Result;
                xml = XDocument.Parse(param);
            }
            //自定义MessageHandler，对微信请求的详细判断操作都在这里面。
            var messageHandler = new CustomMessageHandler(xml, postModel);//接收消息

            messageHandler.Execute();//执行微信处理过程

            return Content(messageHandler.ResponseDocument.ToString());

        }
        IHomeBusiness homeBusiness { get => AutofacHelper.GetScopeService<IHomeBusiness>(); }
        [HttpGet]
        [IgnoreJWT]
        public AjaxResult SubmitLogin(string userName,string password,string code,string appid)
        {
            var res = homeBusiness.SubmitLogin(userName, password);
            if (res.Success)
            {
                Ims_messageuserBusiness _ms_messageuserBus = AutofacHelper.GetScopeService<Ims_messageuserBusiness>();
                var messageuser = _ms_messageuserBus.GetIQueryable().Where(t => t.serviceAppId == appid && t.userId == t.userId).FirstOrDefault();
                if (messageuser.IsNullOrEmpty())
                {
                    messageuser = new PushMessage.Entity.ms_messageuser();
                    messageuser.Id = IdHelper.GetId();
                    messageuser.serviceAppId = appid;
                    messageuser.userId = @operator.UserId;
                    messageuser.userOpenId = code;
                    res=_ms_messageuserBus.AddData(messageuser);
                    if (res.Success)
                    {
                        res = AjaxHelper.Success("新绑定成功");
                        try { 
                        IBase_UserBusiness base_UserBusiness = AutofacHelper.GetScopeService<IBase_UserBusiness>();
                        var user = base_UserBusiness.GetIQueryable().Where(t => t.UserName == userName || t.Telephone == userName).FirstOrDefault();
                        if (user.IsNullOrEmpty())
                        {
                           // return AjaxHelper.Error("用户不存在");
                        }
                        WeiXinApp weiXinApp = new WeiXinApp();
                        weiXinApp.appid = "wxbf54c37d5ef7bd9e";
                        weiXinApp.wxappid = "wx779ab85d1680f09b";
                        weiXinApp.pagepath = "pages/login/index";
                        weiXinApp.userId = user.Id;
                        weiXinApp.templeteId = "t3RbuLdjz0-Ylrfsss058m1bWvK0-E7PCcnj72T4fKk";
                        weiXinApp.messageobj = new { first= new TemplateDataItem(user.UserName), keyword1= new TemplateDataItem(messageuser.Id)
                            , keyword2= new TemplateDataItem("绑定公众号"), keyword3= new TemplateDataItem(DateTime.Now.ToString()), keyword4= new TemplateDataItem("成功")
                            , keyword5= new TemplateDataItem("保卫部")
                        ,remark= new TemplateDataItem("点击跳转小程序")};
                         PushMessageHelper.PushMessagePonit(weiXinApp, "WxOffBindMesssage_User", "公众号绑定推送_用户");
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteLog_LocalTxt("消息推送失败" + ExceptionHelper.GetExceptionAllMsg(ex));
                        }
                    }
                }
                else
                {
                    if(messageuser.userOpenId!= code)
                    {
                        var s=_ms_messageuserBus.RunTransaction(() =>
                        {
                            _ms_messageuserBus.DeleteData(new List<string> { messageuser.Id });
                            messageuser = new PushMessage.Entity.ms_messageuser();
                            messageuser.Id = IdHelper.GetId();
                            messageuser.serviceAppId = appid;
                            messageuser.userId = @operator.UserId;
                            messageuser.userOpenId = code;
                            _ms_messageuserBus.AddData(messageuser);
                        });
                        if (s.Success)
                        {
                            res = AjaxHelper.Success("覆盖绑定成功");
                            try { 
                            IBase_UserBusiness base_UserBusiness = AutofacHelper.GetScopeService<IBase_UserBusiness>();
                            var user = base_UserBusiness.GetIQueryable().Where(t => t.UserName == userName || t.Telephone == userName).FirstOrDefault();
                            if (user.IsNullOrEmpty())
                            {
                                // return AjaxHelper.Error("用户不存在");
                            }
                            WeiXinApp weiXinApp = new WeiXinApp();
                            weiXinApp.appid = "wxbf54c37d5ef7bd9e";
                            weiXinApp.wxappid = "wx779ab85d1680f09b";
                            weiXinApp.pagepath = "pages/login/index";
                            weiXinApp.userId = user.Id;
                            weiXinApp.templeteId = "t3RbuLdjz0-Ylrfsss058m1bWvK0-E7PCcnj72T4fKk";
                            weiXinApp.messageobj = new
                            {
                                first = new TemplateDataItem(user.UserName),
                                keyword1 = new TemplateDataItem(messageuser.Id)
                                ,
                                keyword2 = new TemplateDataItem("绑定公众号"),
                                keyword3 = new TemplateDataItem(DateTime.Now.ToString()),
                                keyword4 = new TemplateDataItem("成功")
                                ,
                                keyword5 = new TemplateDataItem("保卫部")
                            ,
                                remark = new TemplateDataItem("点击跳转小程序")
                            };
                                PushMessageHelper.PushMessagePonit(weiXinApp, "WxOffBindMesssage_User", "公众号绑定推送_用户");
                            }
                            catch (Exception ex)
                            {
                                LogHelper.WriteLog_LocalTxt("消息推送失败" + ExceptionHelper.GetExceptionAllMsg(ex));
                            }
                        }
                        else
                        {
                            res= AjaxHelper.Error(ExceptionHelper.GetExceptionAllMsg(s.ex));
                        }
                    }
                    else
                    {
                        res = AjaxHelper.Success("已经绑定同一账号");
                    }
                }
            }
            return res;
        }
        Ims_messageuserBusiness _MessageuserBusiness { get => AutofacHelper.GetScopeService<Ims_messageuserBusiness>(); }
        [HttpPost]
        [IgnoreJWT]
        public AjaxResult PushMessageApp(WeiXinApp weiXinApp)
        {
            IPMServiceContainer pMServiceContainer = AutofacHelper.GetScopeService<IPMServiceContainer>();
            return pMServiceContainer.PushMessage(weiXinApp);
        }

        [HttpGet]
        [IgnoreJWT]
        public AjaxResult JsSdkSignature(string appId,string url)
        {
            Ims_messageserviceBusiness pMServiceContainer = AutofacHelper.GetScopeService<Ims_messageserviceBusiness>();
            var service=pMServiceContainer.GetIQueryable().Where(t => t.appid == appId&&t.StatusFlag=="1").FirstOrDefault();
            if (service.IsNullOrEmpty())
            {

            }
            var timestamp = JSSDKHelper.GetTimestamp();
            var nonceStr = JSSDKHelper.GetNoncestr();
            string jsapi_ticket = JsApiTicketContainer.TryGetJsApiTicket(appId, "f53fe5c498e6565c74ede0503cbe5b9a");
            string strurl = url;
            var signature = JSSDKHelper.GetSignature(jsapi_ticket, nonceStr, timestamp, strurl);
            return AjaxHelper.Success(new { appId, timestamp, nonceStr, signature });
        }

    }
}